import random
from flask import Flask,request,render_template, Response, stream_with_context
from flask_cors import CORS
import time
import json
import os
from flask_compress import Compress
from configs.config import MyDevelopmentConfig
from flask_socketio import SocketIO,emit,join_room,leave_room
import eventlet
eventlet.monkey_patch()


# 设置static目录
current_dir = os.path.dirname(os.path.abspath(__file__))
staticfolder = os.path.join(current_dir, "static")
app = Flask(__name__,static_folder=staticfolder)
# 从命令行参数获取env值
env = os.environ.get('FLASK_ENV', 'mydev')
if env == "mydev":
    app.config.from_object(MyDevelopmentConfig)

#跨域 https://flask-cors.readthedocs.io/en/3.0.4/api.html#flask_cors.CORS
CORS(app, supports_credentials=True)
# 压缩
Compress(app)
# websocket
socketio=SocketIO()
socketio.init_app(app, cors_allowed_origins='*',async_mode='eventlet')
websocket_namespace='/aigc'



@app.route('/')
def index():
    # return render_template("TestSSEChartdata.html")
    return render_template("TestWebSocket.html")

#测试SSE推送JSON数据
@app.route('/testChartData')
def  test_chartdata():
    def generate_random_data():
        a=0;
        while True:
            a+=1
            if a==100: # 设置如果前端不中止SSE连接，就在a=100时完成数据传输
                break
            json_data=json.dumps({'time':a,'value':random.random()*100})
            # 1 SSE 返回格式是json字符串，要使用yield返回，字符串后面一定要跟随 \n\n
            yield f"data:{json_data}\n\n"
            time.sleep(1) # 1s 发送一次
    # 2 stream_with_context 设置SSE连接函数，mimetype="text/event-stream" 是设置SSE返回格式
    response=Response(stream_with_context(generate_random_data()),mimetype="text/event-stream")
    response.headers["Cache-Control"]="no-cache"
    response.headers["X-Accel-Buffering"]="no"
    response.headers["Connection"] = "keep-alive"
    response.headers["Access-Control-Allow-Origin"] = "*"
    return  response


# 测试websocket
@socketio.on('connect',namespace=websocket_namespace)
def websocket_connect():
    print("websocket connect...ip:{}===sid:{}".format(request.remote_addr,request.sid))
    emit("message",{'msg':'hello!','timestamp':round(time.time()*1000)})

@socketio.on('disconnect',namespace=websocket_namespace)
def websocket_disconnect():
    print("websocket disconnect...")


@socketio.on('message', namespace=websocket_namespace)
def websockettest_message(message):
    print(f'websocket  messageresponse===={request.sid} {message}')









if __name__ == '__main__':
    Host = app.config.get('HOST', '127.0.0.1')  # 使用默认值，以防配置中没有这个值
    PORT = app.config.get('PORT', 8001)  # 使用默认值，以防配置中没有这个值
    Debug = app.config.get('DEBUG', False)  # 使用默认值，以防配置中没有这个值
    print(Host, PORT, Debug)
    # app.run()
    # socketio.run(app, host=Host, port=PORT, debug=Debug)

    socketio.run(app,host='0.0.0.0', port=PORT, debug=Debug)

